﻿var util = {
    has_one: function (items, val) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item == val) {
                return true;
            }
        }

        return false;
    },
    get_one: function (items, key, val) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item[key] == val) {
                return item;
            }
        }

        return null;
    },
    get_max: function (items, key) {
        var max = Math.abs(items[0][key]);
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var val = Math.abs(item[key]);
            if (val > max) {
                max = val;
            }
        }
        return max;
    },
    safe_val: function (val) {
        return val == null ? '' : val.toString();
    },
    random_id: function () {
        var r = Math.floor(1000000 * Math.random());
        var dt = new Date();
        var id = '' + dt.getFullYear() + (dt.getMonth() + 1) + dt.getDate() + dt.getHours() + dt.getMinutes() + dt.getSeconds() + r;
        return id;
    },
    random_num: function (max) {
        return Math.floor(max * Math.random());
    },
    show_num: function (num) {
        if (num == null) {
            return '';
        }

        if (num > 100000000) {
            return Math.floor(100.0 * num / 100000000) / 100 + '亿';
        }

        if (num > 10000000) {
            return Math.floor(10.0 * num / 10000000) / 10 + '千万';
        }

        if (num > 10000) {
            return Math.floor(10.0 * num / 10000) / 10 + '万';
        }

        return num.toString();
    },
    get_real_length: function (input) {
        var count = 0;
        if (!input) {
            return count;
        }
        for (var i = 0; i < input.length; i++) {
            var ch = input[i];
            if (ch.charCodeAt() <= 255) {
                count += 1;
            } else {
                count += 2;
            }
        }
        return count;
    },
    sub_real_length: function (input, count) {
        var sb = '';
        if (!input) {
            return sb;
        }
        var temp_count = 0;
        for (var i = 0; i < input.length; i++) {
            var add = 2;
            var ch = input[i];
            if (ch.charCodeAt() <= 255) {
                add = 1;
            }
            if (temp_count + add > count) {
                break;
            }
            temp_count += add;
            sb += ch;
        }
        return sb;
    },
    get_cell_val: function (val, max) {
        if (val == null) {
            return '<span style="color:#888;font-style:italic;">NULL</span>';
        }

        if (val.toString().trim().length == 0) {
            return '<span style="color:#888;font-style:italic;">空</span>';
        }

        if (!max) {
            max = 10;
        }
        if (util.get_real_length(val.toString()) > max) {
            return '<span title="' + val.toString().replace(/"/g, "'") + '">' + util.sub_real_length(val.toString(), max) + '...</span>';
        }
        return val;
    },
    get_active_attr: function (current, target, attr, attr_val) {
        var active_attr = '';
        if (current == target) {
            active_attr = ' ' + attr + '="' + attr_val + '"';
        }
        return active_attr;
    },
    get_num_str: function (num, unit) {
        if (!unit) {
            unit = 1;
        }

        var val = unit * num;
        if (val > 100000000) {
            return Math.round(100 * val / 100000000) / 100 + '亿';
        }

        if (val > 10000000) {
            return Math.round(10 * val / 10000000) / 10 + '千万';
        }

        if (val > 1000000) {
            return Math.round(10 * val / 1000000) / 10 + '百万';
        }

        if (val > 10000) {
            return Math.round(100 * val / 10000) / 100 + '万';
        }

        return val;
    },
    is_alipay_request: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }
        return ua.toUpperCase().indexOf('ALIPAYCLIENT') > 0;
    },
    is_weixin_request: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }
        return ua.toUpperCase().indexOf('MICROMESSENGER') > 0;
    },
    is_wework_request: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }
        return ua.toUpperCase().indexOf('MICROMESSENGER') > 0;
    },
    is_mobile_request: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }

        ua = ua.toUpperCase();
        if (ua.indexOf('ANDROID') > 0) {
            return true;
        }

        if (ua.indexOf('IPHONE') > 0) {
            return true;
        }

        if (ua.indexOf('IPAD') > 0) {
            return true;
        }

        if (util.is_alipay_request(ua)) {
            return true;
        }

        if (util.is_weixin_request(ua)) {
            return true;
        }

        return false;
    },
    get_device: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }

        ua = ua.toUpperCase();
        if (ua.indexOf('IPHONE') > 0) {
            return 'iPhone';
        }

        if (ua.indexOf('IPAD') > 0) {
            return 'iPad';
        }

        if (ua.indexOf('WINDOWWECHAT') > 0) {
            return '微信PC端';
        }

        return '';
    },
    get_brand: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }

        ua = ua.toUpperCase();
        if (ua.indexOf(' APPLE ') > 0) {
            return '苹果';
        }

        if (ua.indexOf(' HUAWEI ') > 0) {
            return '华为';
        }

        if (ua.indexOf(' OPPO ') > 0) {
            return 'OPPO';
        }

        if (ua.indexOf(' VIVO ') > 0) {
            return 'VIVO';
        }

        return '';
    },
    get_os: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }

        ua = ua.toUpperCase();
        if (ua.indexOf('WINDOWS NT 10.0') > 0) {
            return 'WIN10';
        }

        if (ua.indexOf('WINDOWS NT 6.3') > 0) {
            return 'WIN8.1';
        }

        if (ua.indexOf('WINDOWS NT 6.2') > 0) {
            return 'WIN8';
        }

        if (ua.indexOf('WINDOWS NT 6.1') > 0) {
            return 'WIN7';
        }

        if (ua.indexOf('WINDOWS NT 6.0') > 0) {
            return 'VISTA';
        }

        if (ua.indexOf('WINDOWS NT 5.2') > 0) {
            return 'SERVER2003';
        }

        if (ua.indexOf('WINDOWS NT 5.1') > 0) {
            return 'XP';
        }

        if (ua.indexOf('ANDROID') > 0) {
            return 'ANDROID';
        }

        if (ua.indexOf('OS X') > 0) {
            return 'MacOs';
        }

        if (ua.indexOf('LINUX') > 0) {
            return 'LINUX';
        }

        if (ua.indexOf('UNIX') > 0) {
            return 'UNIX';
        }

        return '';
    },
    get_browser: function (ua) {
        if (!ua) {
            ua = navigator.userAgent.toUpperCase();
        }

        ua = ua.toUpperCase();
        if (ua.indexOf('MSIE') > 0) {
            return 'IE';
        }

        if (ua.indexOf('FIREFOX') > 0) {
            return 'Firefox';
        }

        if (ua.indexOf('CHROME') > 0) {
            return 'Chrome';
        }

        if (ua.indexOf('SAFARI') > 0) {
            return 'Safari';
        }

        return '';
    },
    get_fixed: function (num, n) {
        if (num.toString().length > n) {
            return num;
        }
        return (Array(n).join(0) + num).slice(-n);
    },
    day_of_week: ['周日', '周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    formatdate: function (dt, format) {
        if (!dt) {
            return '';
        }
        if (!format) {
            format = 'yyyy/MM/dd HH:mm:ss';
        }
        format = format.replace("yyyy", dt.getFullYear());
        format = format.replace("MM", util.get_fixed(dt.getMonth() + 1, 2));
        format = format.replace("dd", util.get_fixed(dt.getDate(), 2));
        format = format.replace("HH", util.get_fixed(dt.getHours(), 2));
        format = format.replace("mm", util.get_fixed(dt.getMinutes(), 2));
        format = format.replace("ss", util.get_fixed(dt.getSeconds(), 2));
        return format;
    },
    formatdate2: function (datestr, format) {
        if (!datestr) {
            return '';
        }
        var dt_input = parseInt(datestr.substr(6));
        var dt = new Date(dt_input);
        return util.formatdate(dt, format);
    },
    formatdate3: function (timestamp, format) {
        if (!timestamp) {
            return '';
        }
        var dt = new Date(timestamp);
        return util.formatdate(dt, format);
    },
    formatdate4: function (datestr, format) {
        if (!datestr) {
            return '';
        }
        var dt_input = datestr.replace('T', ' ').replace(/-/g, '/');
        var dt = new Date(dt_input);
        return util.formatdate(dt, format);
    },
    add_days: function (days, dt) {
        if (!dt) {
            dt = new Date();
        }

        dt.setDate(dt.getDate() + days);
        return dt;
    },
    fast_day_range: function (days) {
        var dt1 = util.formatdate(util.add_days(0 - days), 'yyyy-MM-dd');
        return dt1 + ',';
    },
    ts_display: function (dt, dt2) {
        if (!dt2) {
            dt2 = new Date();
        }
        var ts = dt2.getTime() - new Date(dt).getTime();
        ts = ts / 1000;
        if (ts > 3 * 24 * 3600) {
            return util.formatdate(dt, 'yyyy-MM-dd');
        } else if (ts > 24 * 3600) {
            return Math.floor(ts / (24 * 3600)) + '天';
        } else if (ts > 3600) {
            return Math.floor(ts / (3600)) + '小时';
        } else if (ts > 60) {
            return Math.floor(ts / 60) + '分钟';
        } else {
            return Math.floor(ts) + '秒';
        }
    },
    ts_days_display: function (dt1, dt2, onlyDays) {
        var t1;
        var t2;
        if (onlyDays) {
            t1 = new Date(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()).getTime();
            t2 = new Date(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()).getTime();
        } else {
            t1 = dt1.getTime();
            t2 = dt2.getTime();
        }
        var ts = t2 - t1;
        ts = ts / 1000;
        var days = Math.floor(ts / (24 * 3600));
        return days;
    },
    sort_items: function (items, sort_func) {
        for (var i = 0; i < items.length; i++) {
            for (var j = i; j < items.length; j++) {
                if (sort_func(items[i], items[j])) {
                    var temp = items[i];
                    items[i] = items[j];
                    items[j] = temp;
                }
            }
        }
    },
    render_items: function (items, render_func) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            render_func(item, i);
        }
    },
    get_distance_km: function (x1, y1, x2, y2) {
        var distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
        var distance_km = Math.floor(1000 * distance) / 10;
        return distance_km;
    },
    copy_text: function (text) {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text)
                .then(function () {
                    util.show_toast('已复制', '#22b14c');
                })
                .catch(function (e) {
                    var msg = '复制失败';
                    if (e) {
                        msg += '，' + e;
                    }
                    util.show_toast(msg, '#ed1c24');
                });
        } else {
            var textarea = document.createElement('textarea');
            textarea.style.position = 'fixed';
            textarea.style.opacity = 0;
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
        }
    },
    get_fixed: function (num, n) {
        if (num.toString().length > n) {
            return num;
        }
        return (Array(n).join(0) + num).slice(-n);
    },
    formatdate: function (dt, format) {
        if (!dt) {
            return '';
        }
        if (!format) {
            format = 'yyyy/MM/dd HH:mm:ss';
        }
        format = format.replace("yyyy", dt.getFullYear());
        format = format.replace("MM", util.get_fixed(dt.getMonth() + 1, 2));
        format = format.replace("dd", util.get_fixed(dt.getDate(), 2));
        format = format.replace("HH", util.get_fixed(dt.getHours(), 2));
        format = format.replace("mm", util.get_fixed(dt.getMinutes(), 2));
        format = format.replace("ss", util.get_fixed(dt.getSeconds(), 2));
        return format;
    },
    formatdate2: function (datestr, format) {
        if (!datestr) {
            return '';
        }
        var dt = new Date(parseInt(datestr.substr(6)));
        return util.formatdate(dt, format);
    },
    formatdate3: function (datelong, format) {
        if (!datelong) {
            return '';
        }
        var dt = new Date(datelong);
        return util.formatdate(dt, format);
    },
    formatdate4: function (datestr, format) {
        if (!datestr) {
            return '';
        }
        var dt2 = datestr.replace('T', ' ').replace(/-/g, '/');
        var dt = new Date(dt2);
        return util.formatdate(dt, format);
    },
    show_toast_timer: null,
    show_toast: function (msg, bgColor, color, ms) {
        if (!bgColor) {
            bgColor = 'var(--bg1)';
        }

        if (!color) {
            color = '#fff';
        }

        if (ms == null) {
            ms = 1500;
        }

        var el_id = "_div_toast_container";
        var el = document.getElementById(el_id);
        if (!el) {
            el = document.createElement('div');
            el.setAttribute('id', el_id);
            el.style.width = '300px';
            el.style.position = 'fixed';
            el.style.left = '50%';
            el.style.top = '50%';
            el.style.marginLeft = '-150px';
            el.style.overflow = 'hidden';
            el.style.zIndex = '10010';
            document.body.appendChild(el);
        }

        el.style.display = 'block';
        var toast_id = '_div_toast_' + new Date().getTime() + Math.floor(1000000 * Math.random());
        var sb = '';
        sb += '<div id="' + toast_id + '" style="text-align:center;margin-bottom:10px;"><span style="display:inline-block;box-shadow:0 0 2px #000;padding:10px 20px;border-radius:8px;background-color:' + bgColor + ';color:' + color + ';">' + msg + '</span></div>';

        var html = $(el).html();
        html = sb + html;
        $(el).html(html);

        if (ms > 0) {
            setTimeout(function () {
                $('#' + toast_id).remove();
            }, ms);

            util.show_toast_timer = setInterval(function () {
                if ($('#' + el_id).children().length == 0) {
                    clearInterval(util.show_toast_timer)
                    $('#' + el_id).hide();
                }
            }, 100);
        }
    },
    hide_toast: function (el_id) {
        var el = document.getElementById(el_id);
        if (el) {
            el.style.display = 'none';
        }
    },
    filesize: function (size) {
        if (size >= 1024 * 1024 * 1024) {
            return Math.floor(100 * size / (1024 * 1024 * 1024)) / 100 + 'GB';
        } else if (size >= 1024 * 1024) {
            return Math.floor(10 * size / (1024 * 1024)) / 10 + 'MB';
        } else if (size >= 1024) {
            return Math.floor(10 * size / 1024) / 10 + 'KB';
        } else {
            return size + 'B';
        }
    },
    debounce: function (func, delay) {
        if (!delay) {
            delay = 1500;
        }
        let timer;
        return function () {
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                func.apply(this, arguments);
            }, delay);
        };
    },
    foreach: function (items, func) {
        if (!items || items.length == 0) {
            return;
        }
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            func && func(item, i);
        }
    }
};